import logging

from libs.redis_wrapper import RedisWrapper
from config import CONTRACT_EXPIRES_MIN

logging.basicConfig(level=logging.INFO)


class RedisLoginAuth(object):

    @staticmethod
    def bytes_str(token):
        if isinstance(token, bytes):
            token = token.decode("utf8")
        return token

    def __init__(self, token, prefix):
        self.token = RedisLoginAuth.bytes_str(token)
        # self.conn = conn
        self.token_prefix = prefix + "_" + "UT" + "_"
        self.count_prefix = prefix + "_" + "UC" + "_"
        # self.sql_rid_prefix=sql_rid_prefix
        self.sql_count_prefix = prefix + "_" + "SC" + "_"

    def get_uid(self) -> int:
        uid = RedisLoginAuth.bytes_str(RedisWrapper.get(self.token_prefix + self.token))
        if uid:
            return int(uid)
        else:
            return 0

    def is_count_lte_limit(self) -> int:
        uid = str(self.get_uid())
        if uid:
            uid = str(uid)
            _count = RedisLoginAuth.bytes_str(RedisWrapper.get(self.count_prefix + uid))
            limit_count = RedisLoginAuth.bytes_str(RedisWrapper.get(self.sql_count_prefix + uid))
            if not limit_count:
                limit_count = '0'
            return int(_count) <= int(limit_count)
        else:
            return 0

    def update_expire_second(self, expire_second=24 * 60 * 60 * CONTRACT_EXPIRES_MIN):
        RedisWrapper.expire(self.token_prefix + self.token, expire_second)
        uid = RedisLoginAuth.bytes_str(RedisWrapper.get(self.token_prefix + self.token))
        RedisWrapper.expire(self.token_prefix + uid, expire_second)
        RedisWrapper.expire(self.count_prefix + uid, expire_second)

    def remove_login_redis(self):
        RedisWrapper.remove(self.token_prefix + self.token)

    def login_init(self, uid: str, limit_count: str, expire_second=24 * 60 * 60 * CONTRACT_EXPIRES_MIN):
        """
        #登陆成功初始化，需要初始化：
        #token->uid
        #uid->token
        #uid->count
        #先删除已有的token,这一步实现了登陆互踢
        """
        if isinstance(uid, int):
            uid = str(uid)

        if isinstance(limit_count, int):
            limit_count = str(limit_count)

        # 再更新
        # token->uid
        RedisWrapper.set(self.token_prefix + self.token, uid)
        RedisWrapper.expire(self.token_prefix + self.token, expire_second)
        # uid->token
        RedisWrapper.set(self.token_prefix + uid, self.token)
        RedisWrapper.expire(self.token_prefix + uid, expire_second)
        # uid->action count
        RedisWrapper.set(self.count_prefix + uid, 0)
        RedisWrapper.expire(self.count_prefix + uid, expire_second)
        # uid->rid

        RedisWrapper.set(self.sql_count_prefix + uid, limit_count)
        RedisWrapper.expire(self.sql_count_prefix + uid, expire_second)
